package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CAshGateVideoBind;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CWeightSheets;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CpyScoreExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CpyScoreExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICWeightSheetsService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CWeightSheetsMapper;
import com.xiaoxu.intranetweb.util.SzResult;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.Future;

@Component
@Slf4j
public class MonthlyTrendBu {
    @Autowired
    private CWeightSheetsMapper cWeightSheetsMapper;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ICWeightSheetsService icWeightSheetsService;

    /**
     * 月度出货量趋势
     *
     * @param year 年份
     * @return
     */
    public SzResult monthlyWeightTrend(int year, String token,String plantId) throws Exception {
//        按照品种遍历分组
        List<MonthlyWeightTrendVo> monthlyWeightTrendVos = cWeightSheetsMapper.monthlyWeightTrend(year,  plantId);
//        遍历出所有品种存入list
        List<String> list1 = new ArrayList();
        for (MonthlyWeightTrendVo monthlyWeightTrendVo : monthlyWeightTrendVos) {
            list1.add(monthlyWeightTrendVo.getProduct());
        }
//        新建一个map
        Map<String, List<MonthlyWeightTrendVo>> map = new HashMap<>();
//      根据品种分组存入map
        for (String s : list1) {
            List<MonthlyWeightTrendVo> list2 = new ArrayList<>();
            for (MonthlyWeightTrendVo monthlyWeightTrendVo : monthlyWeightTrendVos) {
                if (s.equals(monthlyWeightTrendVo.getProduct())) {
                    list2.add(monthlyWeightTrendVo);
                }
            }
            map.put(s, list2);
        }
        return SzResult.success(map);
    }

    /**
     * 月底销售额趋势
     *
     * @param year 年份
     * @return
     */
    public SzResult monthlyMoneyTrend(int year, String token,String plantId) throws Exception {
//        按照品种遍历分组
        List<MonthlyMoneyTrendVo> monthlyWeightTrendBOS = cWeightSheetsMapper.monthlyMoneyTrend(year,  plantId);
//        遍历出所有品种存入list
        List<String> list1 = new ArrayList();
        for (MonthlyMoneyTrendVo monthlyWeightTrendBO : monthlyWeightTrendBOS) {
            list1.add(monthlyWeightTrendBO.getProduct());
        }
//        新建一个map
        Map<String, List<MonthlyMoneyTrendVo>> map = new HashMap<>();
//      根据品种分组存入map
        for (String s : list1) {
            List<MonthlyMoneyTrendVo> list2 = new ArrayList<>();
            for (MonthlyMoneyTrendVo monthlyWeightTrendBO : monthlyWeightTrendBOS) {
                if (s.equals(monthlyWeightTrendBO.getProduct())) {
                    list2.add(monthlyWeightTrendBO);
                }
            }
            map.put(s, list2);
        }
        return SzResult.success(map);
    }
//    AnnualWeightTrend

    /**
     * 年度出货量趋势
     *
     * @param year 年份
     * @return
     */
    public SzResult annualWeightTrend(int year, String token,String plantId) throws Exception {
//        按照品种遍历分组
        List<AnnualWeightTrendVo> monthlyWeightTrendBOS = cWeightSheetsMapper.yearlyWeightTrend(year, plantId);
//        遍历出所有品种存入list
        List<String> list1 = new ArrayList();
        for (AnnualWeightTrendVo monthlyWeightTrendBO : monthlyWeightTrendBOS) {
            list1.add(monthlyWeightTrendBO.getProduct());
        }
//        新建一个map
        Map<String, List<AnnualWeightTrendVo>> map = new HashMap<>();
//      根据品种分组存入map
        for (String s : list1) {
            List<AnnualWeightTrendVo> list2 = new ArrayList<>();
            for (AnnualWeightTrendVo monthlyWeightTrendBO : monthlyWeightTrendBOS) {
                if (s.equals(monthlyWeightTrendBO.getProduct())) {
                    list2.add(monthlyWeightTrendBO);
                }
            }
            map.put(s, list2);
        }
        return SzResult.success(map);
    }
    // yearlyMoneyTrend

    /**
     * 年度销售额趋势
     *
     * @param year 年份
     * @return
     */
    public SzResult annualMoneyTrend(int year, String token,String plantId) throws Exception {
//        按照品种遍历分组
        List<AnnualMoneyTrendVo> monthlyWeightTrendBOS = cWeightSheetsMapper.yearlyMoneyTrend(year,  plantId);
//        遍历出所有品种存入list
        List<String> list1 = new ArrayList();
        for (AnnualMoneyTrendVo monthlyWeightTrendBO : monthlyWeightTrendBOS) {
            list1.add(monthlyWeightTrendBO.getProduct());
        }
//        新建一个map
        Map<String, List<AnnualMoneyTrendVo>> map = new HashMap<>();
//      根据品种分组存入map
        for (String s : list1) {
            List<AnnualMoneyTrendVo> list2 = new ArrayList<>();
            for (AnnualMoneyTrendVo monthlyWeightTrendBO : monthlyWeightTrendBOS) {
                if (s.equals(monthlyWeightTrendBO.getProduct())) {
                    list2.add(monthlyWeightTrendBO);
                }
            }
            map.put(s, list2);
        }
        return SzResult.success(map);
    }

    /**
     * 各公司年度物流占比
     */

    public SzResult cpyYearLogistics(String token, String cpy, String cpyChi, String year,String plantId) throws Exception {
        String yearStart = "2000" + "-01-01";
        String yearEnd = LocalDateTime.now().getYear() + "-12-31";
        if (year != null && !year.equals("")) {
            yearStart = year + "-01-01";
            yearEnd = year + "-12-31";
        }
        List<CpyYearLogisticsVo> list = cWeightSheetsMapper.cpyYearLogistics( plantId, yearStart, yearEnd);
        Integer total = 0;
        for (CpyYearLogisticsVo cpyYearLogisticsVo : list) {
            Integer subTotal = cpyYearLogisticsVo.getSubTotal();
            total += subTotal;
        }
        for (CpyYearLogisticsVo cpyYearLogisticsVo : list) {
            cpyYearLogisticsVo.setTotal(total);
            String percent = "0.00%";
            if (total != 0) {
                percent = new DecimalFormat("0.00").format((float) cpyYearLogisticsVo.getSubTotal() / (float) total * 100) + "%";
            }
            cpyYearLogisticsVo.setPercent(percent);
        }
        if (cpy != null && !cpy.equals("")) {
            if (cpyChi != null && !cpyChi.equals("")) {
                //只要符合条件的
                List<CpyYearLogisticsVo> list1 = new ArrayList<>();
                for (CpyYearLogisticsVo cpyYearLogisticsVo : list) {
                    if (cpyYearLogisticsVo.getCpy().equals(cpy) && cpyYearLogisticsVo.getCpyChi().equals(cpyChi)) {
                        list1.add(cpyYearLogisticsVo);
                    }
                }
                return SzResult.success(list1);
            }
        }
        return SzResult.success(list);
    }


    /**
     * 各公司年度销售额占比
     */
    public SzResult cpyYearMoney(String token, String year,String plantId) throws Exception {
        String yearStart = "2000" + "-01-01";
        String yearEnd = LocalDateTime.now().getYear() + "-12-31";
        if (year != null && !year.equals("")) {
            yearStart = year + "-01-01";
            yearEnd = year + "-12-31";
        }
        List<CpyYearMoneyVo> list = cWeightSheetsMapper.cpyYearMoney(plantId, yearStart, yearEnd);
        Integer total = 0;
        for (CpyYearMoneyVo cpyYearMoneyVo : list) {
            if (cpyYearMoneyVo.getSubTotal()!=null) {
                Integer subTotal = cpyYearMoneyVo.getSubTotal();
                total += subTotal;
            }else {
                total += 0;
            }
        }
        for (CpyYearMoneyVo cpyYearMoneyVo : list) {
            cpyYearMoneyVo.setTotal(total);
            String percent = "0.00%";
            if (total != 0) {
                percent = new DecimalFormat("0.00").format((float) cpyYearMoneyVo.getSubTotal() / (float) total * 100) + "%";
            }
            cpyYearMoneyVo.setPercent(percent);
        }
        return SzResult.success(list);
    }


    /**
     * 各货物年度出货量占比
     */
    public SzResult productYearWeight(String token, String year,String plantId) throws Exception {
        String yearStart = "2000" + "-01-01";
        String yearEnd = LocalDateTime.now().getYear() + "-12-31";
        if (year != null && !year.equals("")) {
            yearStart = year + "-01-01";
            yearEnd = year + "-12-31";
        }
        List<ProductYearWeightVo> list = cWeightSheetsMapper.productYearWeight( plantId, yearStart, yearEnd);
        Integer total = 0;
        for (ProductYearWeightVo productYearWeightVo : list) {
            Integer subTotal = productYearWeightVo.getWeight();
            total += subTotal;
        }
        for (ProductYearWeightVo productYearWeightVo : list) {
            productYearWeightVo.setTotalWeight(total);
            String percent = "0.00%";
            if (total != 0) {
                percent = new DecimalFormat("0.00").format((float) productYearWeightVo.getWeight() / (float) total * 100) + "%";
            }
            productYearWeightVo.setPercent(percent);
        }
        return SzResult.success(list);
    }


    /**
     * 各货物年度收款占比
     */
    public SzResult productYearMoney(String token, String year,String plantId) throws Exception {
        String yearStart = "2000" + "-01-01";
        String yearEnd = LocalDateTime.now().getYear() + "-12-31";
        if (year != null && !year.equals("")) {
            yearStart = year + "-01-01";
            yearEnd = year + "-12-31";
        }
        List<ProductYearMoneyVo> list = cWeightSheetsMapper.productYearMoney( plantId, yearStart, yearEnd);
        Integer total = 0;
        for (ProductYearMoneyVo productYearMoneyVo : list) {
            if (productYearMoneyVo.getMoney() !=null) {
                Integer subTotal = productYearMoneyVo.getMoney();
                total += subTotal;
            }else {
                total += 0;
            }
        }
        for (ProductYearMoneyVo productYearMoneyVo : list) {
            if (productYearMoneyVo.getMoney() != null) {
                productYearMoneyVo.setTotalMoney(total);
                String percent = "0.00%";
                if (total != 0) {
                    percent = new DecimalFormat("0.00").format((float) productYearMoneyVo.getMoney() / (float) total * 100) + "%";
                }
                productYearMoneyVo.setPercent(percent);
            }
        }
        return SzResult.success(list);
    }


    /**
     * 客户业绩考核表
     */
    public SzResult cpyScore(String token, String timeStart, String timeEnd,String plantId) throws Exception {
        //传过来的是2022-01和2022-12,要的是传过来的第一个月份的第一天的零时零分零秒 到传过来的第二个月份的最后一天的23时59分59秒

        if (timeStart != null && timeEnd != null) {
            LocalDate firstDayOfMonth1 = LocalDate.parse(timeStart + "-01"); // 获取第一个月份的第一天
            LocalDate lastDayOfMonth2 = LocalDate.parse(timeEnd + "-01").withDayOfMonth(LocalDate.parse(timeEnd + "-01").lengthOfMonth()); // 获取第二个月份的最后一天
            LocalDateTime startDateTime = LocalDateTime.of(firstDayOfMonth1, LocalTime.MIN); // 第一个月份的第一天的零时零分零秒
            LocalDateTime endDateTime = LocalDateTime.of(lastDayOfMonth2, LocalTime.MAX); // 第二个月份的最后一天的23时59分59秒
            timeStart = startDateTime.toString().replace("T", " ");
            timeEnd = endDateTime.toString().replace("T", " ");
        }
        List<CpyScoreVo> list = cWeightSheetsMapper.cpyScore(plantId, timeStart, timeEnd);
        int totalWeight = 0;
        int totalMoney = 0;
        for (CpyScoreVo cpyScoreVo : list) {
            Integer weight = cpyScoreVo.getWeight();
            Integer money = cpyScoreVo.getMoney();
            totalWeight += weight;
            totalMoney += money;
        }
        for (CpyScoreVo cpyScoreVo : list) {
            cpyScoreVo.setTotalWeight(totalWeight);
            cpyScoreVo.setTotalMoney(totalMoney);
            String percent1 = "0.00%";
            String percent2 = "0.00%";
            String totalScore = "0.00%";
            if (totalWeight != 0) {
                percent1 = new DecimalFormat("0.00").format((float) cpyScoreVo.getWeight() / (float) totalWeight * 100) + "%";
            }
            if (totalMoney != 0) {
                percent2 = new DecimalFormat("0.00").format((float) cpyScoreVo.getMoney() / (float) totalMoney * 100) + "%";
            }
            percent1 = percent1.substring(0, percent1.length() - 1);
            percent2 = percent2.substring(0, percent2.length() - 1);
            //打印percent1和percent2

            cpyScoreVo.setWeightScore(percent1);
            cpyScoreVo.setMoneyScore(percent2);
            totalScore = String.valueOf(Float.parseFloat(percent1) + Float.parseFloat(percent2)) + "%";

            totalScore = totalScore.substring(0, totalScore.length() - 1);
            //totalScore保留两位小数
            totalScore = new DecimalFormat("0.00").format(Float.parseFloat(totalScore)) + "%";
            totalScore = totalScore.substring(0, totalScore.length() - 1);
            cpyScoreVo.setTotalScore(totalScore);
        }
        list.sort(new Comparator<CpyScoreVo>() {
            @Override
            public int compare(CpyScoreVo o1, CpyScoreVo o2) {
                //降序
                String substring = o2.getTotalScore().substring(0, o2.getTotalScore().length() - 1);
                String substring1 = o1.getTotalScore().substring(0, o1.getTotalScore().length() - 1);
                double v = Double.parseDouble(substring);
                double v1 = Double.parseDouble(substring1);
                return Double.compare(v, v1);
            }
        });
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRank(i + 1);
        }

        //在所有数据后面加上一行总计
        CpyScoreVo cpyScoreVo = new CpyScoreVo();
        cpyScoreVo.setCpyCo("总计");
        cpyScoreVo.setWeight(totalWeight);
        cpyScoreVo.setMoney(totalMoney);
//        cpyScoreVo.setMoneyScore("100.00%");
//        cpyScoreVo.setWeightScore("100.00%");
        cpyScoreVo.setTotalScore("200.00");
        //将cpyScoreVo放到list的最后一行
        list.add(cpyScoreVo);
        return SzResult.success(list);
    }

    /**
     * 客户业绩考核表导出excel
     */
    @Async


    public Future<List<CpyScoreExcelEn>> cpyScoreExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean isHeader, String mode,
                                                       Boolean original, Map<String, String> pager, String sheetName, String token, String timeStart, String timeEnd,String plantId) throws Exception {


        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<CpyScoreExcelEn> poundQueryExcelEns = new ArrayList<>();
// 判断 mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//            newIds为Map<String, Object>类型，需要转换为PoundQueryExcelBo类型
//            遍历newIds
                    for (Map<String, Object> newId : newIds) {
//                创建一个PoundQueryExcelBo对象
                        CpyScoreExcelEn cpyScoreExcelEn = CpyScoreExcelEn.builder().build();
//                遍历newId
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("cpyChiCo")) {
                                cpyScoreExcelEn.setCpyChiCo(entry.getValue().toString());
                            }
                            if (entry.getKey().equals("cpyCo")) {
                                cpyScoreExcelEn.setCpyCo(entry.getValue().toString());
                            }
                            if (entry.getKey().equals("money")) {
                                cpyScoreExcelEn.setMoney(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("moneyScore")) {
                                cpyScoreExcelEn.setMoneyScore(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("weight")) {
                                cpyScoreExcelEn.setWeight(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("weightScore")) {
                                cpyScoreExcelEn.setWeightScore(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("totalScore")) {
                                cpyScoreExcelEn.setTotalScore(entry.getValue().toString());
                            }
                            if (entry.getKey().equals("rank")) {
                                cpyScoreExcelEn.setRank(entry.getValue().toString());
                            }
                        }
//                存入poundQueryExcelBos
                        poundQueryExcelEns.add(cpyScoreExcelEn);
                    }
                    break;
                case "all":
//                    为全部时直接调用查询方法cpyScoreVo
                    SzResult result = this.cpyScore(token, timeStart, timeEnd,plantId);
                    Object result1 = result.getResult();
                    //将result1转换为List<CpyScoreVo>
                    List<CpyScoreVo> list = (List<CpyScoreVo>) result1;
                    //List<CpyScoreVo> list = cWeightSheetsMapper.cpyScore(userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId(), timeStart, timeEnd);
                    for (CpyScoreVo cpyScoreVo : list) {
                        CpyScoreExcelEn cpyScoreExcelEn = CpyScoreExcelEn.builder().build();
                        cpyScoreExcelEn.setCpyCo(cpyScoreVo.getCpyCo());
                        cpyScoreExcelEn.setCpyChiCo(cpyScoreVo.getCpyChiCo());
                        cpyScoreExcelEn.setMoney(new BigDecimal(String.valueOf(cpyScoreVo.getMoney())));
                        cpyScoreExcelEn.setWeight(new BigDecimal(String.valueOf(cpyScoreVo.getWeight())));
                        cpyScoreExcelEn.setMoneyScore(new BigDecimal(cpyScoreVo.getMoneyScore()));
                        cpyScoreExcelEn.setWeightScore(new BigDecimal(cpyScoreVo.getWeightScore()));
                        cpyScoreExcelEn.setTotalScore(cpyScoreVo.getTotalScore());
                        cpyScoreExcelEn.setRank(String.valueOf(cpyScoreVo.getRank()));
                        poundQueryExcelEns.add(cpyScoreExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//            newIds为Map<String, Object>类型，需要转换为PoundQueryExcelBo类型
//            遍历newIds
                    for (Map<String, Object> newId : newIds) {
//                创建一个PoundQueryExcelBo对象
                        CpyScoreExcelEn cpyScoreExcelEn = CpyScoreExcelEn.builder().build();
//                遍历newId
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("cpyChiCo")) {
                                cpyScoreExcelEn.setCpyChiCo(entry.getValue().toString());
                            }
                            if (entry.getKey().equals("cpyCo")) {
                                cpyScoreExcelEn.setCpyCo(entry.getValue().toString());
                            }
                            if (entry.getKey().equals("money")) {
                                cpyScoreExcelEn.setMoney(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("moneyScore")) {
                                cpyScoreExcelEn.setMoneyScore(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("weight")) {
                                cpyScoreExcelEn.setWeight(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("weightScore")) {
                                cpyScoreExcelEn.setWeightScore(new BigDecimal(entry.getValue().toString()));
                            }
                            if (entry.getKey().equals("totalScore")) {
                                cpyScoreExcelEn.setTotalScore(entry.getValue().toString());
                            }
                            if (entry.getKey().equals("rank")) {
                                cpyScoreExcelEn.setRank(entry.getValue().toString());
                            }
                        }
//                存入poundQueryExcelBos
                        poundQueryExcelEns.add(cpyScoreExcelEn);
                    }
                    break;
                default:
                    break;
            }
            return new AsyncResult<>(poundQueryExcelEns);
        } catch (Exception e) {
//使用slf4j打印异常信息：导出poundQueryExcelBos失败
            log.error("导出poundQueryExcelBos失败", e);
            return null;
        }
    }
}
